from PySide6.QtCore import QThread, Signal
from ...base import ThreadBase
from watermarker.marker import im_add_mark
from PIL import Image
from pathlib import Path
from traceback import format_exc
from .conversion import *


class ImgAddMarkThread(ThreadBase):
    progressed = Signal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.text = None
        self.img_files = None
        self.save_path = None
        self.color = None
        self.size = None
        self.opacity = None
        self.space = None
        self.angle = None

    def run(self):
        save_path = Path(self.save_path)
        if not save_path.exists():
            save_path.mkdir()
        fl = len(self.img_files)
        for index, img_file in enumerate(self.img_files):
            self.progressed.emit(f'正在添加水印，进度：{index} / {fl}，请稍后...')

            try:
                img_path = Path(img_file)
                name = img_path.stem + '（水印）' + img_path.suffix
                im = Image.open(img_file)
                image = im_add_mark(im, self.text, self.color, self.size, self.opacity, self.space, self.angle)
                if img_path.suffix != '.png':
                    image = image.convert('RGB')
                image.save(str(save_path / name))
            except Exception as e:
                print(format_exc())
                self.error.emit(f'{img_file} 水印添加失败,\n {e}')

    def set_value(self, text, img_files: list, save_path, color="#8B8B1B", size=30, opacity=0.15, space=75, angle=30):
        self.text = text
        self.img_files = img_files
        self.save_path = save_path
        self.color = color
        self.size = size
        self.opacity = opacity
        self.space = space
        self.angle = angle
